package com.moleq.mgpos.activities;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsoluteLayout;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.moleq.adapter.ItemListAdapter;
import com.moleq.adapter.MixMatchSelectionAdapter;
import com.moleq.base.MoleQBaseActivity;
import com.moleq.base.MoleQBaseDialog;
import com.moleq.device.BaseScanner;
import com.moleq.device.DeviceManager;
import com.moleq.device.DeviceSettingService;
import com.moleq.device.ScannerSetting;
import com.moleq.dialog.DateSettingSelectionDialog;
import com.moleq.dialog.GlobalPriceChangeDialog2;
import com.moleq.dialog.InputDateInfoDialog;
import com.moleq.dialog.InputTimeInfoDialog;
import com.moleq.dialog.ItemDiscountDialog;
import com.moleq.dialog.MessageDialog;
import com.moleq.dialog.TimeSettingSelectionDialog;
import com.moleq.dialog.MessageDialog.OnClickMessageListener;
import com.moleq.itemsetting.tools.MGCreateFiles;
import com.moleq.logic.UPC;
import com.moleq.models.Departmant;
import com.moleq.models.GlobalInfo;
import com.moleq.models.ItemDiscountSetting;
import com.moleq.models.ItemSetting;
import com.moleq.models.MixMatch;
import com.moleq.models.MixMatch_detail;
import com.moleq.models.PosSetting;
import com.moleq.models.PriceSetting;
import com.moleq.service.DepartmantService;
import com.moleq.service.ItemPicService;
import com.moleq.service.ItemSettingService;
import com.moleq.service.MixMatchService;
import com.moleq.service.MixMatchSettingService;
import com.moleq.service.PriceService;
import com.moleq.service.ServiceManager;
import com.moleq.util.MoleQUtil;

public class PriceSettingActivity extends MoleQBaseActivity {
	/** Called when the activity is first created. */

	private Spinner sp_list;
	private String[] sp_items;
	private Button btn_search, btn_update, btn_exit, btn_dialog_ok,
			btn_dialog_cancel, btn_undo,btn_mm,btn_globalpricechange,btn_discount_link;
	private ImageButton ibtn_nextpage, ibtn_backpage, ibtn_clear_date,ibtn_clear_mm,ibtn_clear_dis_link;
	private TextView tv_dupc, tv_dname, tv_ddesc, tv_dprice;
	private ItemSettingService itemservice = null;
	private PriceService priceservice = null;
	private DepartmantService depService;
	private MixMatchService mmservice = null;
	private MixMatchSettingService mmSettingservice = null;
	private List<ItemSetting> itemlist = null;
	private List<MixMatch_detail> MMlist = null;
	private ItemListAdapter itemAdapter;
	private MixMatchSelectionAdapter MMAdapter;
	private ListView lv_items,lv_dialog_list;
	public EditText et_cp_amt, et_cp_price, et_da_price, et_et_date,
			et_et_time, et_lq_amt, et_lq_price, et_np_amt;
	public EditText et_np_price, et_percent_amt, et_pp_amt, et_pp_price,
			et_search, et_st_date, et_st_time,et_price_lvl;
	private TextView tv_page;
	private ImageView iv_photo;
	private int searchType = 0;
	private String searchString = "";
	private int PageCountSize = 0;
	private DeviceSettingService mSettingService;
	private DeviceManager mDeviceManager;
	static final int DATE_DIALOG_ID_S = 0;
	static final int DATE_DIALOG_ID_E = 1;
	static final int TIME_DIALOG_ID_S = 2;
	static final int TIME_DIALOG_ID_E = 3;
	private int mYear, mMonth, mDay;
	private LinearLayout  ll_search;
	private String price_type = "";
	private MessageDialog mMessageDialog;
	private static GlobalPriceChangeDialog2 mGpcDialog;
	private int ScaleControlID;
	private static ItemDiscountDialog mDisLinkItemDiscountDialog;
	private static ItemDiscountSetting dis;
	private String disLink = "";
	public static int Pricemode = 0;
	private MGCreateFiles mMGCreateFiles = new MGCreateFiles();
	private ItemPicService mItemPicService;
	private AbsoluteLayout ll_price_detail;
	private DateSettingSelectionDialog mdssDialog;
	private InputDateInfoDialog ididDialog;
	
	private TimeSettingSelectionDialog tdssDialog;
	private InputTimeInfoDialog itidDialog;
	
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_price_setting);


		getcontroller();
		SetEnabledTrue();
		InitializeEnabledFalse();
		// =========== setup scanner =================
		mDeviceManager = DeviceManager.getInstance();
		mSettingService = ServiceManager.getInstance().mDeviceSettingService;
		mItemPicService = ServiceManager.getInstance().mItemPicService;
		
		List<ScannerSetting> scannerSettings = mSettingService
				.getScannerSettings();

		// check scanner
		int iScannerCount = scannerSettings.size();
		for (int i = 0; i < iScannerCount; i++) {
			int iPort = scannerSettings.get(i).getPort();
			for (int j = i + 1; j < iScannerCount; j++) {
				if (iPort == scannerSettings.get(j).getPort()) {
					// Toast.makeText(PriceSettingActivity.this,
					// " Scanner setup error. Please check.",
					// Toast.LENGTH_LONG).show();
					ShowMessage(" Scanner setup error. Please check.",
							MessageDialog.MESSAGE_BOX_OK,
							MessageDialog.ICON_INFO);
					finish();
				}

			}
		}

		for (int i = 0; i < scannerSettings.size(); i++) {
			BaseScanner baseScanner = new BaseScanner();
			baseScanner.setScannerSetting(scannerSettings.get(i));
			mDeviceManager.addScanner(baseScanner);
		}

		// open scanner
		for (int i = 0; i < mDeviceManager.scanners.size(); i++) {
			mDeviceManager.scanners.get(i).onConnect();
			mDeviceManager.scanners.get(i).setCallbackEvent(this);
			mDeviceManager.scanners.get(i).onEnableScanner();
		}

		// ============================================
	}

	public void getcontroller() {

		sp_list = (Spinner) findViewById(R.id.sp_condition);
		sp_items = getResources().getStringArray(R.array.sp_condition_name);
		ArrayAdapter<String> SpAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, sp_items);
		SpAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		sp_list.setAdapter(SpAdapter);
		sp_list.setOnItemSelectedListener(onItemSelectedListener);

		ll_price_detail = (AbsoluteLayout)findViewById(R.id.ll_price_detail);
		
		lv_items = (ListView) findViewById(R.id.lv_item);

		tv_page = (TextView) findViewById(R.id.tv_page);

		iv_photo = (ImageView) findViewById(R.id.iv_photo);

		ll_search = (LinearLayout) findViewById(R.id.ll_search);

		et_search = (EditText) findViewById(R.id.et_search);
		et_cp_amt = (EditText) findViewById(R.id.et_cp_amt);
		et_cp_price = (EditText) findViewById(R.id.et_cp_price);
		et_da_price = (EditText) findViewById(R.id.et_da_price);
		et_et_date = (EditText) findViewById(R.id.et_et_date);
		et_et_time = (EditText) findViewById(R.id.et_et_time);
		et_lq_amt = (EditText) findViewById(R.id.et_lq_amt);
		et_lq_price = (EditText) findViewById(R.id.et_lq_price);
		et_np_amt = (EditText) findViewById(R.id.et_np_amt);
		et_np_price = (EditText) findViewById(R.id.et_np_price);
		et_percent_amt = (EditText) findViewById(R.id.et_percent_amt);
		et_pp_amt = (EditText) findViewById(R.id.et_pp_amt);
		et_pp_price = (EditText) findViewById(R.id.et_pp_price);
		et_search = (EditText) findViewById(R.id.et_search);
		et_st_date = (EditText) findViewById(R.id.et_st_date);
		et_st_time = (EditText) findViewById(R.id.et_st_time);
		et_price_lvl = (EditText) findViewById(R.id.et_price_lvl);		
		//
		tv_dupc = (TextView) findViewById(R.id.tv_dupc);
		tv_dname = (TextView) findViewById(R.id.tv_dname);
		tv_ddesc = (TextView) findViewById(R.id.tv_ddesc);
		tv_dprice = (TextView) findViewById(R.id.tv_dprice);

		ibtn_backpage = (ImageButton) findViewById(R.id.ibtn_backpage);
		ibtn_nextpage = (ImageButton) findViewById(R.id.ibtn_nextpage);
		ibtn_clear_date = (ImageButton) findViewById(R.id.ibtn_clear_date);
		ibtn_clear_mm = (ImageButton) findViewById(R.id.ibtn_clear_mm);
		ibtn_clear_dis_link = (ImageButton) findViewById(R.id.ibtn_clear_dis_link);
		
		btn_exit = (Button) findViewById(R.id.btn_exit);
		btn_mm = (Button) findViewById(R.id.btn_mm);
		btn_search = (Button) findViewById(R.id.btn_search);
		btn_globalpricechange = (Button) findViewById(R.id.btn_globalpricechange);
		btn_update = (Button) findViewById(R.id.btn_update);
		btn_undo = (Button) findViewById(R.id.btn_undo);
		lv_items.setOnItemClickListener(onItemClickListener);
		btn_discount_link = (Button) findViewById(R.id.btn_dis_link);
		
		btn_exit.setOnClickListener(onClickListener);
		btn_update.setOnClickListener(onClickListener);
		btn_search.setOnClickListener(onClickListener);
		btn_globalpricechange.setOnClickListener(onClickListener);
		ibtn_backpage.setOnClickListener(onClickListener);
		ibtn_nextpage.setOnClickListener(onClickListener);
		ibtn_clear_date.setOnClickListener(onClickListener);
		ibtn_clear_mm.setOnClickListener(onClickListener);
		ibtn_clear_dis_link.setOnClickListener(onClickListener);
		btn_undo.setOnClickListener(onClickListener);
		btn_mm.setOnClickListener(onClickListener);
		ll_search.setOnClickListener(onClickListener);
		btn_discount_link.setOnClickListener(onClickListener);
		ll_price_detail.setOnClickListener(onClickListener);

		et_st_date.setOnClickListener(onTextClickListener);
		et_st_time.setOnClickListener(onTextClickListener);
		et_et_date.setOnClickListener(onTextClickListener);
		et_et_time.setOnClickListener(onTextClickListener);
		lv_items.setOnItemClickListener(onItemClickListener);

		et_cp_amt.addTextChangedListener(itemwatcher);
		et_cp_price.addTextChangedListener(itemwatcher);

		et_da_price.addTextChangedListener(watcher);
		et_et_date.addTextChangedListener(watcher);
		et_et_time.addTextChangedListener(watcher);
		et_lq_amt.addTextChangedListener(watcher);
		et_lq_price.addTextChangedListener(watcher);
		et_np_amt.addTextChangedListener(watcher);
		et_np_price.addTextChangedListener(watcher);
		et_percent_amt.addTextChangedListener(watcher);
		et_pp_amt.addTextChangedListener(watcher);
		et_pp_price.addTextChangedListener(watcher);
		btn_mm.addTextChangedListener(watcher);
		btn_discount_link.addTextChangedListener(watcher);
		et_st_date.addTextChangedListener(watcher);
		et_st_time.addTextChangedListener(watcher);
		et_price_lvl.addTextChangedListener(watcher);

		itemservice = ServiceManager.getInstance().mItemSettingService;
		priceservice = ServiceManager.getInstance().mPriceService;
		mmservice = ServiceManager.getInstance().mMixMatchService;
		depService = ServiceManager.getInstance().mDepartmantService;
		mmSettingservice = ServiceManager.getInstance().mMixMatchSettingService;
		mDisLinkItemDiscountDialog = new ItemDiscountDialog(PriceSettingActivity.this, PriceSettingActivity.this);
		
		mdssDialog = new DateSettingSelectionDialog(this);
		tdssDialog = new TimeSettingSelectionDialog(this);
		itidDialog = new InputTimeInfoDialog(this, this);
		ididDialog = new InputDateInfoDialog(this, this);
		PosSetting item = ServiceManager.getInstance().mPosSettingService.Find();
		if(item == null){
			GlobalInfo.getInstance().calendar_type = false;
		}else{
			GlobalInfo.getInstance().calendar_type = item.isCalendarType();
		}
		
		ibtn_backpage.setVisibility(View.INVISIBLE);
		ibtn_nextpage.setVisibility(View.INVISIBLE);
		tv_page.setText("");
	}

	public OnItemClickListener onItemClickListener = new OnItemClickListener() {

		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			Pricemode = 0;
			Keyboard();
			itemAdapter.ScrollToRow(position);
			RefresItem(position);

			Pricemode = 1;
		}

	};

	private TextWatcher itemwatcher = new TextWatcher() {

		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
		}

		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
		}

		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub
			if (Pricemode == 1) {
				SetEnabledFalse();// Fasle
				price_type = "1";
			}

		}
	};

	private TextWatcher watcher = new TextWatcher() {

		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
		}

		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
		}

		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub

			if (Pricemode == 1) {
				SetEnabledFalse();// Fasle
			}
		}
	};

	public void RefresItem(int position) {
		String upc = null;

		if (itemlist != null) {
			upc = itemlist.get(position).getUpc();
			tv_dupc.setText(upc);
			tv_dname.setText(itemlist.get(position).getName());
			tv_ddesc.setText(itemlist.get(position).getDesc());
			String priceText = "";
			if (itemlist.get(position).getMultple() > 1) {
				priceText = String.valueOf(itemlist.get(position).getMultple()) + "/";
			}
			tv_dprice.setText(priceText+String.format("%.2f",itemlist.get(position).getPrice()));
			Bitmap bp = mItemPicService.getImageByUPC(upc);
			if (bp == null) {
				Bitmap logo = BitmapFactory.decodeResource(PriceSettingActivity.this
						.getApplicationContext().getResources(),
						R.drawable.moleqlogo);
				iv_photo.setImageBitmap(logo);
			} else {
				iv_photo.setImageBitmap(bp);
			}
			itemAdapter.ScrollToRow(position);
			RefresItemPrice(upc);

			InitializeEnabledTrue();
		}

	}

	public void RefresItemPrice(String upc) {
		PriceSetting price = new PriceSetting();
		ItemSetting itemSetting = new ItemSetting();
		price = priceservice.getitemprice(upc);
		itemSetting = itemservice.findByUpc(upc);
		dis = null;
		
		et_price_lvl.setText(String.valueOf(price.getPrice_lvl()));
		et_cp_amt.setText((itemSetting.getMultple() <= 1) ? "" : String.valueOf(price.getCurrentqty()));
		et_cp_price.setText(String.format("%.2f", Double.valueOf(price.getRetailprice())));
		if (price == null) {
			setempty();
		} else {

			et_da_price.setText((price.getDiscountamount() == null) ? ""
					: String.format("%.2f",Double.valueOf(price.getDiscountamount())));

			et_et_date.setText(getdatetime(price.getEnddate() == null ?"":String.valueOf(price.getEnddate())));
			et_et_time.setText(gettime(price.getEndtime()));

			et_lq_amt.setText((price.getLimitedqtyamount() == null || Integer
					.valueOf(price.getLimitedqtyamount()) < 1) ? "" : String
					.valueOf(price.getLimitedqtyamount()));
			et_lq_price.setText((price.getLimitedqtyprice() == null) ? ""
					: String.format("%.2f",
							Double.valueOf(price.getLimitedqtyprice())));
			et_np_amt.setText((price.getPriceMultiple() == null || Integer
					.valueOf(price.getPriceMultiple()) <= 1) ? "" : String
					.valueOf(price.getPriceMultiple()));

			et_np_price.setText((price.getPrice() == null) ? "" : String.format("%.2f", Double.valueOf(price.getPrice())));
			et_percent_amt.setText((price.getDiscountpercent() == null || Double.valueOf(price.getDiscountpercent()) < 0) ? "": String.format("%.2f",Double.valueOf(price.getDiscountpercent())));
			et_pp_amt.setText((price.getPackagepricemultiple() == null || Integer.valueOf(price.getPackagepricemultiple()) <= 1) ? "": String.valueOf(price.getPackagepricemultiple()));
			et_pp_price.setText((price.getPackageprice() == null) ? "" : String.format("%.2f", Double.valueOf(price.getPackageprice())));
//			et_st_date.setText(getdatetime(price.getStartdate()));
			et_st_date.setText(getdatetime(price.getStartdate() == null ?"":String.valueOf(price.getStartdate())));
			et_st_time.setText(gettime(price.getStarttime()));
			btn_mm.setText((price.getPricemm() == null) ? "" : String.valueOf(price.getPricemm()));
			disLink = (price.getDislink() == null) ? "" : price.getDislink();
			String ls_dis_name = ServiceManager.getInstance().mDiscountSettingService.getItemDiscountName(disLink.equals("")?"0":disLink);		
			btn_discount_link.setText((ls_dis_name == null) ? "" : String.valueOf(ls_dis_name));
			 
			
		}
	}

	public String getdatetime(String date) {

		Date curDate = null;
		String str;
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		DateFormat format1 = new SimpleDateFormat("yyyyMMdd");
		// Date curDate =(Date)date;
		try {
			if(date == null) return "";
			curDate = format1.parse(date);

		} catch (ParseException e) {
			e.printStackTrace();
		}
		if (curDate == null) {
			str = "";
		} else {
			str = formatter.format(curDate);
		}
		return str;
	};

	public String gettime(String time) {

		if (time == null || time.equals("")) {
			return "";
		} else {
			String str = time.substring(0, 2);
			String str2 = time.substring(2);
			return str + ":" + str2;
		}

	};

	public int gettime_short(String time) {

		int str;
		if (time == null) {
			str = 0;
		} else {
			str = Integer.valueOf(time.replace(":", ""));
		}
		return str;

	};

	public void setempty() {

		et_da_price.setText("");
		et_et_date.setText("");
		et_et_time.setText("");
		et_lq_amt.setText("");
		et_lq_price.setText("");
		et_np_amt.setText("");
		et_np_price.setText("");
		et_percent_amt.setText("");
		et_pp_amt.setText("");
		et_pp_price.setText("");
		et_st_date.setText("");
		et_st_time.setText("");
		btn_mm.setText("");
		btn_discount_link.setText("");
	}

	
	public OnClickListener onTextClickListener = new OnClickListener() {

		public void onClick(View view) {
			
			switch (view.getId()) {

			case R.id.et_st_date:
				if (GlobalInfo.getInstance().calendar_type) {
					mdssDialog.show(R.id.et_st_date,et_st_date.getText().toString());
				}else{
					ididDialog.show(R.id.et_st_date,et_st_date.getText().toString());
				}
				break;
			case R.id.et_st_time:
				if (GlobalInfo.getInstance().calendar_type) {
					tdssDialog.show(R.id.et_st_time,et_st_time.getText().toString());
				}else{
					itidDialog.show(R.id.et_st_time,et_st_time.getText().toString());
				}
				break;
			case R.id.et_et_date:
				if (GlobalInfo.getInstance().calendar_type) {
					mdssDialog.show(R.id.et_et_date,et_et_date.getText().toString());
				}else{
					ididDialog.show(R.id.et_et_date,et_et_date.getText().toString());
				}
				break;
			case R.id.et_et_time:
				if (GlobalInfo.getInstance().calendar_type) {
					tdssDialog.show(R.id.et_et_time,et_et_time.getText().toString());
				}else{
					itidDialog.show(R.id.et_et_time,et_et_time.getText().toString());
				}
				break;
			}

		}

	};

//	public void setdate(int id) {
//
//		EditText et_date = (EditText) findViewById(id);
//		String ls_date = et_date.getText().toString();
//
//		Date curDate = null;
//		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
//		// Date curDate =(Date)date;
//		try {
//
//			curDate = format1.parse(ls_date);
//
//		} catch (ParseException e) {
//			e.printStackTrace();
//		}
//
//		Calendar c1 = Calendar.getInstance();
//
//		if (curDate == null) {
//			mYear = c1.get(Calendar.YEAR);
//			mMonth = c1.get(Calendar.MONTH);
//			mDay = c1.get(Calendar.DAY_OF_MONTH);
//		} else {
//			c1.setTime(curDate);
//			mYear = c1.get(Calendar.YEAR);
//			mMonth = c1.get(Calendar.MONTH);
//			mDay = c1.get(Calendar.DAY_OF_MONTH);
//		}
//
//	}

//	public void settime(int id) {
//
//		EditText et_time = (EditText) findViewById(id);
//		String ls_time = et_time.getText().toString();
//
//		if (ls_time.equals("") || ls_time == null) {
//			Calendar c1 = Calendar.getInstance();
//			hour = c1.get(Calendar.HOUR_OF_DAY);
//			minute1 = c1.get(Calendar.MINUTE);
//
//		} else {
//			String hourOfDay = ls_time.substring(0, 2);
//			String minute = ls_time.substring(3);
//
//			hour = Integer.valueOf(hourOfDay);
//			minute1 = Integer.valueOf(minute);
//
//		}
//
//	}
//
//	OnDateSetListener mDateSetListener = new OnDateSetListener() {
//		public void onDateSet(DatePicker view, int year, int monthOfYear,
//				int dayOfMonth) {
//			String date;
//			mYear = year;
//			mMonth = monthOfYear;
//			mDay = dayOfMonth;
//
//			date = (new StringBuilder().append(mYear).append("-")
//					.append(String.format("%02d", mMonth + 1)).append("-")
//					.append(String.format("%02d", mDay))).toString();
//
//			if (datetype.equals("st_date")) {
//				et_st_date.setText(date);
//				if (et_st_time.getText().toString().equals("")) {
//					et_st_time.setText("00:00");
//				}
//			} else {
//				et_et_date.setText(date);
//
//				if (et_et_time.getText().toString().equals("")) {
//					et_et_time.setText("23:59");
//				}
//			}
//
//		}
//	};

//	protected Dialog onCreateDialog(int id) {
//		switch (id) {
//		case DATE_DIALOG_ID_S:
//			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
//					mDay);
//		case DATE_DIALOG_ID_E:
//
//			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
//					mDay);
//		case TIME_DIALOG_ID_S:
//			return new TimePickerDialog(this, mTimeSetListener, hour, minute1,
//					true);
//		case TIME_DIALOG_ID_E:
//			return new TimePickerDialog(this, mTimeSetListener, hour, minute1,
//					true);
//		}
//
//		return null;
//	};
//
//	@Override
//	public void onPrepareDialog(int id, Dialog dialog) {
//		switch (id) {
//		case DATE_DIALOG_ID_S:
//			removeDialog(DATE_DIALOG_ID_S);
//			break;
//		case DATE_DIALOG_ID_E:
//			removeDialog(DATE_DIALOG_ID_E);
//			break;
//		case TIME_DIALOG_ID_S:
//			removeDialog(TIME_DIALOG_ID_S);
//			break;
//		case TIME_DIALOG_ID_E:
//			removeDialog(TIME_DIALOG_ID_E);
//			break;
//
//		}
//	}
//
//	OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
//
//		@Override
//		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
//			// TODO Auto-generated method stub
//			String time;
//			hour = hourOfDay;
//			minute1 = minute;
//
//			Calendar c1 = Calendar.getInstance();
//			mYear = c1.get(Calendar.YEAR);
//			mMonth = c1.get(Calendar.MONTH) + 1;
//			mDay = c1.get(Calendar.DAY_OF_MONTH);
//			time = String.format("%02d", hour) + ":"
//					+ String.format("%02d", minute1);
//
//			if (timetype.equals("st_time")) {
//				et_st_time.setText(time);
//				et_st_date.setText(mYear + "-" + mMonth + "-" + mDay);
//			} else {
//				et_et_time.setText(time);
//				et_et_date.setText(mYear + "-" + mMonth + "-" + mDay);
//			}
//		}
//
//	};

	public OnClickListener onClickListener = new OnClickListener() {

		public void onClick(View view) {

			String pagetext = "", upc;
			String da_price, et_date, et_time, lq_amt, lq_price, np_amt, np_price, percent_amt, pp_amt, pp_price, st_date, st_time, pmm, cp_price, cp_amt, et_lvl;
			 
			int page, index;

			switch (view.getId()) {

			case R.id.ibtn_clear_date:
				et_date = et_et_date.getText().toString();
				et_time = et_et_time.getText().toString();
				st_date = et_st_date.getText().toString();
				st_time = et_st_time.getText().toString();
				if (!et_date.equals("") || !et_time.equals("")
						|| !st_date.equals("") || !st_time.equals("")) {
					et_et_date.setText("");
					et_et_time.setText("");
					et_st_date.setText("");
					et_st_time.setText("");
				}

				break;
			case R.id.ibtn_clear_mm:
				if (!btn_mm.getText().equals("")) {
					btn_mm.setText("");
				}
				
				break;
			case R.id.ibtn_clear_dis_link:
				if (!btn_discount_link.getText().equals("")) {
					btn_discount_link.setText("");
					dis = null;
					disLink = "";
				}
				
				break;
			case R.id.et_cp_amt:
				et_cp_amt.clearFocus();
				break;
			case R.id.et_cp_price:
				et_cp_price.clearFocus();
				break;
			case R.id.btn_undo:
				// SaveMode = "";
				// if (listAdapter == null) return;
				index = Integer.valueOf(itemAdapter.GetSelectedIndex());

				int size = itemlist.size();
				if (index >= 0 && size > 0) {

					Pricemode = 0;
					RefresItem(index);
					Pricemode = 1;
				}
				// et_no.setEnabled(false);
				SetEnabledTrue();
				SetPage();
				price_type = "0";
				break;
			case R.id.btn_update:

				if (itemlist.size() <= 0) {
					return;
				}
				Keyboard();
				index = itemAdapter.GetSelectedIndex();
				upc = itemlist.get(index).getUpc();
				PriceSetting price = new PriceSetting();
				MixMatch mm = new MixMatch();

				if (validation() < 0) {
					return;
				}
				et_lvl = et_price_lvl.getText().toString();
				cp_price = et_cp_price.getText().toString();
				cp_amt = et_cp_amt.getText().toString();
				da_price = et_da_price.getText().toString();
				et_date = et_et_date.getText().toString();
				et_time = et_et_time.getText().toString();
				lq_amt = et_lq_amt.getText().toString();
				lq_price = et_lq_price.getText().toString();
				np_amt = et_np_amt.getText().toString();
				np_price = et_np_price.getText().toString();
				percent_amt = et_percent_amt.getText().toString();
				pp_amt = et_pp_amt.getText().toString();
				pp_price = et_pp_price.getText().toString();
				st_date = et_st_date.getText().toString();
				st_time = et_st_time.getText().toString();
				pmm = btn_mm.getText().toString();
				if (dis != null) {
					disLink = String.valueOf(dis.getDs_no());	
				}
				
			   
				
				price.setUpc(upc);
				price.setPriceMultiple((np_amt.equals("")) ? null : np_amt);
				price.setPrice((np_price.equals("")) ? null : np_price);
				price.setStartdate((st_date.equals("")) ? null: st_date);
				price.setStarttime((st_time.equals("")) ? null: st_time);
				price.setEnddate((et_date.equals("")) ? null: et_date);
				price.setEndtime((et_time.equals("")) ? null: et_time);
				price.setPackagepricemultiple((pp_amt.equals("")) ? null: pp_amt);
				price.setPackageprice((pp_price.equals("")) ? null : pp_price);
				price.setLimitedqtyamount((lq_amt.equals("")) ? null : lq_amt);
				price.setLimitedqtyprice((lq_price.equals("")) ? null: lq_price);
				price.setDiscountamount((da_price.equals("")) ? null: da_price);
				price.setDiscountpercent((percent_amt.equals("")) ? null: percent_amt);
				price.setPricemm((pmm.equals("")) ?null : pmm);
				price.setDislink((disLink.equals("")) ?null : disLink);
				price.setPrice_lvl(et_lvl);
				
				mm.setUpc(upc);
				mm.setMm_no((pmm.equals("")) ? 0 : Integer.valueOf(pmm));

				Pricemode = 0;
				if (price_type.equals("1")) {
					itemservice.updatePrice(cp_price, cp_amt, upc);
					itemlist.get(index).setMultple(cp_amt);
					itemlist.get(index).setPrice(Double.valueOf(cp_price));
					
					 if (GlobalInfo.getInstance().isMGNetwork) {
						 ItemSetting item = itemservice.findByUpc(upc);
						mMGCreateFiles.createrFile(item.toMGData("UPDATE"));//UPDATE,DELETE
					}
				}

				if (priceservice.checkitemprice(upc) == false) {

//					if () {
						priceservice.InsertPrice(price);
						
						 Toast.makeText(PriceSettingActivity.this,
						 "Save completed.",
						 Toast.LENGTH_SHORT).show();
						 
						 if (GlobalInfo.getInstance().isMGNetwork) {
							 PriceSetting pricesetting = priceservice.getitempricesetting(upc);
							mMGCreateFiles.createrFile(pricesetting.toMGData("INSERT"));//UPDATE,DELETE
						}
//						ShowMessage("Save completed.",
//								MessageDialog.MESSAGE_BOX_OK,
//								MessageDialog.ICON_INFO);
//					} else {
//						// Toast.makeText(PriceSettingActivity.this,
//						// "Save Error.",
//						// Toast.LENGTH_LONG).show();
//						ShowMessage("Save Error.",
//								MessageDialog.MESSAGE_BOX_OK,
//								MessageDialog.ICON_INFO);
//						return;
//					}
				} else {
//					if ( > 0) {
						priceservice.UpdatePriceSetting(price);
						
						 Toast.makeText(PriceSettingActivity.this,
						 "Save completed.",
						 Toast.LENGTH_SHORT).show();
						 
						 if (GlobalInfo.getInstance().isMGNetwork) {
							 PriceSetting pricesetting = priceservice.getitempricesetting(upc);
							mMGCreateFiles.createrFile(pricesetting.toMGData("UPDATE"));//UPDATE,DELETE
						}
//						ShowMessage("Save completed.",
//								MessageDialog.MESSAGE_BOX_OK,
//								MessageDialog.ICON_INFO);
//					} else {
//						// Toast.makeText(PriceSettingActivity.this,
//						// "Save Error.",
//						// Toast.LENGTH_LONG).show();
//						ShowMessage("Save Error.",
//								MessageDialog.MESSAGE_BOX_OK,
//								MessageDialog.ICON_ERROR);
//						return;
//					}

				}

				if (!mmservice.checkMixMatch(upc) && !pmm.equals("")) {

					mmservice.InsertMixMatch(mm);
					
					 if (GlobalInfo.getInstance().isMGNetwork) {
						 MixMatch mmSetting = mmservice.FindMmByUPC(upc);
						mMGCreateFiles.createrFile(mmSetting.toMGData("INSERT"));//UPDATE,DELETE
					}
				} else {

					if (pmm.equals("")) {
						
						if (GlobalInfo.getInstance().isMGNetwork) {
							
							 MixMatch mmSetting = mmservice.FindMmByUPC(upc);
							if (mmSetting != null) mMGCreateFiles.createrFile(mmSetting.toMGData("DELETE"));//UPDATE,DELETE
						}
						mmservice.DeleteMm(upc);
						
					} else {

						mmservice.UpdateMixMatch(mm);
						
						if (GlobalInfo.getInstance().isMGNetwork) {
							 MixMatch mmSetting = mmservice.FindMmByUPC(upc);
							 if (mmSetting != null) mMGCreateFiles.createrFile(mmSetting.toMGData("UPDATE"));//UPDATE,DELETE
						}
					}

				}
				
				deletePrice(upc);

				price_type = "0";

				RefresItem(index);
				Pricemode = 1;
				SetEnabledTrue();
				SetPage();
				break;
			case R.id.ll_price_detail:
				Keyboard();
				break;
			case R.id.ll_search:
				Keyboard();
				break;
			case R.id.btn_search:
				Pricemode = 0;
				Keyboard();
				String search = et_search.getText().toString();

				if (search.equals("")) {
					Pricemode = 1;
					return;
				}
				
				tv_page.setText(String.valueOf(1));
				Search();
				et_search.setText("");
				Pricemode = 1;
				break;
			case R.id.btn_globalpricechange:
				//global price change
				if(mGpcDialog == null){
					mGpcDialog = new GlobalPriceChangeDialog2(PriceSettingActivity.this);
					mGpcDialog.show();
				}else{
					if (mGpcDialog.isShowing()) {
						mGpcDialog.dismiss();
					}
					mGpcDialog = new GlobalPriceChangeDialog2(PriceSettingActivity.this);
					mGpcDialog.show();
				}
				
				
				break;
			case R.id.btn_exit:
				// ShowMessage(
				// getResources().getString(R.string.msg_exit_program),
				// MessageDialog.ICON_INFO,
				// MessageDialog.MESSAGE_BOX_YES_NO);
				ShowMessage(
						getResources().getString(R.string.msg_exit_program),
						MessageDialog.MESSAGE_BOX_YES_NO,
						MessageDialog.ICON_INFO);
				break;
			case R.id.ibtn_backpage:
				Pricemode = 0;
				pagetext = (String) tv_page.getText();
				page = Integer.valueOf(pagetext);
				tv_page.setText(String.valueOf(page - 1));
				BindingData((page - 2), searchType, searchString);
				SetPage();
				Pricemode = 1;
				break;
			case R.id.ibtn_nextpage:
				Pricemode = 0;
				pagetext = (String) tv_page.getText();
				page = Integer.valueOf(pagetext);
				tv_page.setText(String.valueOf(page + 1));
				BindingData(page, searchType, searchString);
				SetPage();
				Pricemode = 1;
				break;
				
			case R.id.btn_mm:
				
				index = itemAdapter.GetSelectedIndex();
				upc = itemlist.get(index).getUpc();
				
				Departmant dep = depService.Find(itemlist.get(index).getDep());
				
				if (itemlist.get(index).getFollowdep().equals("1")?true:false) {
					if (dep !=null) {
						itemlist.get(index).setScaleWeight(dep.getScale_weight()?"1":"0");
					}
				}
				
				if (itemlist.get(index).getScaleWeight().equals("1")?true:false) {
					ShowMessage("A scalable item cannot be added into a mix match group.",
							MessageDialog.MESSAGE_BOX_OK,
							MessageDialog.ICON_INFO);
					return;
				}
				
				ScaleControlID = R.id.btn_mm;
				DialogWindows();
				break;
			case R.id.btn_dis_link:
				if (mDisLinkItemDiscountDialog == null || mDisLinkItemDiscountDialog.isShowing())
					return;

				mDisLinkItemDiscountDialog.show();
				break;
			}
		}
	};
	
	public void deletePrice(String upc){
		
		PriceSetting mPriceSetting = null;
		mPriceSetting = priceservice.getitempricesetting(upc);
		if (mPriceSetting != null) {
			if ((mPriceSetting.getStartdate() == null || mPriceSetting
					.getStartdate().trim().equals(""))
					&& (mPriceSetting.getStarttime() == null || mPriceSetting
							.getStarttime().trim().equals(""))
					&& (mPriceSetting.getEnddate() == null || mPriceSetting
							.getEnddate().trim().equals(""))
					&& (mPriceSetting.getEndtime() == null || mPriceSetting
							.getEndtime().trim().equals(""))
					&& (mPriceSetting.getPriceMultiple() == null || mPriceSetting
							.getPriceMultiple().trim().equals(""))
					&& (mPriceSetting.getPrice() == null || mPriceSetting
							.getPrice().trim().equals(""))
					&& (mPriceSetting.getPackagepricemultiple() == null || mPriceSetting
							.getPackagepricemultiple().trim().equals(""))
					&& (mPriceSetting.getPackageprice() == null || mPriceSetting
							.getPackageprice().trim().equals(""))
					&& (mPriceSetting.getLimitedqtyamount() == null || mPriceSetting
							.getLimitedqtyamount().trim().equals(""))
					&& (mPriceSetting.getLimitedqtyprice() == null || mPriceSetting
							.getLimitedqtyprice().trim().equals(""))
					&& (mPriceSetting.getDiscountamount() == null || mPriceSetting
							.getDiscountamount().trim().equals(""))
					&& (mPriceSetting.getDiscountpercent() == null || mPriceSetting
							.getDiscountpercent().trim().equals(""))
					&& (mPriceSetting.getPricemm() == null || mPriceSetting
							.getPricemm().trim().equals(""))
					&& (mPriceSetting.getDislink() == null || mPriceSetting
							.getDislink().trim().equals(""))
					&& (mPriceSetting.getPrice_lvl() == null || mPriceSetting
							.getPrice_lvl().trim().equals(""))) {
				priceservice.DeletePriceSetting(upc);
				if (GlobalInfo.getInstance().isMGNetwork) {
					mMGCreateFiles
							.createrFile(mPriceSetting.toMGData("DELETE"));// UPDATE,DELETE
				}
			}
		}
	}
	
	Dialog DialogWindow = null;

	private void DialogWindows() {
		if (DialogWindow == null) {
			DialogWindow = new Dialog(this, R.style.dialog2);
			DialogWindow.setContentView(R.layout.price_mm_dialog_perview_models);
		}
		lv_dialog_list = (ListView) DialogWindow
				.findViewById(R.id.lv_dialog_list);
		btn_dialog_ok = (Button) DialogWindow.findViewById(R.id.btn_dialog_ok);
		btn_dialog_cancel = (Button) DialogWindow
				.findViewById(R.id.btn_dialog_cancel);
		lv_dialog_list.setOnItemClickListener(onItemClickDialogWindowListener);
		btn_dialog_ok.setOnClickListener(OnClickDialogWindowListener);
		btn_dialog_cancel.setOnClickListener(OnClickDialogWindowListener);

		//lv_dialog_list.setTag(String.valueOf(Group));
		MMlist = mmSettingservice.getmmdetaillist();
		if (MMAdapter == null) {
			MMAdapter = new MixMatchSelectionAdapter(this, MMlist);
			lv_dialog_list.setAdapter(MMAdapter);
		} else {
			MMAdapter.setSource(MMlist);
			MMAdapter.notifyDataSetChanged();
		}
		
		DialogWindow.show();
	}
	
	OnItemClickListener onItemClickDialogWindowListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			MMAdapter.ScrollToRow(position);
		}

	};
	
	OnClickListener OnClickDialogWindowListener = new OnClickListener() {

		@Override
		public void onClick(View view) {
			// TODO Auto-generated method stub
			switch (view.getId()) {
			case R.id.btn_dialog_ok:
				if (MMlist.size() > 0) {
					String value = String.valueOf(MMlist.get(MMAdapter.GetSelectedIndex()).getMs_no());
					Button btn_ScaleControl = (Button) findViewById(ScaleControlID);
					btn_ScaleControl.setText(value);
				}
				DialogWindow.dismiss();
				break;
			case R.id.btn_dialog_cancel:
				DialogWindow.dismiss();
				break;
			}
		}

	};
	
	public int validation() {

		String da_price, et_date, et_time, lq_amt, lq_price, np_amt, np_price, percent_amt, pp_amt, pp_price, st_date, st_time, pmm, cp_price, cp_amt, et_lvl;

		et_lvl = et_price_lvl.getText().toString();
		cp_price = et_cp_price.getText().toString();
		cp_amt = et_cp_amt.getText().toString();
		da_price = et_da_price.getText().toString();
		et_date = et_et_date.getText().toString();
		et_time = et_et_time.getText().toString();
		lq_amt = et_lq_amt.getText().toString();
		lq_price = et_lq_price.getText().toString();
		np_amt = et_np_amt.getText().toString();
		np_price = et_np_price.getText().toString();
		percent_amt = et_percent_amt.getText().toString();
		pp_amt = et_pp_amt.getText().toString();
		pp_price = et_pp_price.getText().toString();
		st_date = et_st_date.getText().toString();
		st_time = et_st_time.getText().toString();
		pmm = btn_mm.getText().toString();
		boolean zeroPrice = false;
		zeroPrice = GlobalInfo.getInstance().isZeroPrice;

		if (et_lvl.equals("")) {
			ShowMessage("Price Level can not be empty.",
					MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
			return -1;
		}
		
		if (Integer.valueOf(et_lvl) <= 0) {
			ShowMessage("Please enter a valid Price Level.",
					MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
			return -1;
		}
		
		if (!et_lvl.equals("") && MoleQUtil.isNumeric2(et_lvl) == false) {
			ShowMessage("Please enter a valid Price Level.",
					MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
			return -1;
		}
		
		if (!cp_amt.equals("") && cp_price.equals("")) {
			// Toast.makeText(PriceSettingActivity.this,
			// "Current Price can not be empty.",
			// Toast.LENGTH_LONG).show();
			ShowMessage("Current Price can not be empty.",
					MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
			return -1;
		}

		if (!cp_price.equals("") && isNum(cp_price) == false) {
			// Toast.makeText(PriceSettingActivity.this,
			// "Please enter a valid Current Price.",
			// Toast.LENGTH_LONG).show();
			ShowMessage("Please enter a valid Current Price.",
					MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
			return -1;
		}
		
		if (!cp_price.equals("") && Double.valueOf(cp_price) == 0 && !zeroPrice) {
			ShowMessage("Item Price cannot be zero.",
					MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
			et_cp_price.requestFocus();
			return -1;
		}

		if (!np_amt.equals("") && np_price.equals("")) {
			// Toast.makeText(PriceSettingActivity.this,
			// "Next Price can not be empty.",
			// Toast.LENGTH_LONG).show();
			ShowMessage("Next Price can not be empty.",
					MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
			return -1;
		}

		if (!np_price.equals("") && isNum(np_price) == false) {
			// Toast.makeText(PriceSettingActivity.this,
			// "Please enter a valid Next Price.",
			// Toast.LENGTH_LONG).show();
			ShowMessage("Please enter a valid Next Price.",
					MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
			return -1;
		}
		
		if (!np_price.equals("") && Double.valueOf(np_price) == 0 && !zeroPrice) {
			ShowMessage("Item Price cannot be zero.",
					MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
			et_np_price.requestFocus();
			return -1;
		}

		if (!pp_amt.equals("") && pp_price.equals("")) {
			// Toast.makeText(PriceSettingActivity.this,
			// "Pkg Price can not be empty.",
			// Toast.LENGTH_LONG).show();
			ShowMessage("Pkg Price can not be empty.",
					MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
			return -1;
		}

		if (!pp_price.equals("") && isNum(pp_price) == false) {
			// Toast.makeText(PriceSettingActivity.this,
			// "Please enter a valid Pkg Price.",
			// Toast.LENGTH_LONG).show();
			ShowMessage("Please enter a valid Pkg Price.",
					MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
			return -1;
		}
		
		if (!pp_price.equals("") && Double.valueOf(pp_price) == 0 && !zeroPrice) {
			ShowMessage("Item Price cannot be zero.",
					MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
			et_pp_price.requestFocus();
			return -1;
		}
		
		if (da_price.equals("0")) {
			ShowMessage("Discount Amount can not be zero.",
					MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
			return -1;
		}
		
		if (percent_amt.equals("0")) {
			ShowMessage("Discount Rate can not be zero.",
					MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
			return -1;
		}
		
		if (lq_amt.equals("0")) {
			// Toast.makeText(PriceSettingActivity.this,
			// "Limited Price can not be empty.",
			// Toast.LENGTH_LONG).show();
			ShowMessage("Limited Qty can not be zero.",
					MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
			return -1;
		}
		
		if (!lq_price.equals("") && lq_amt.equals("")) {
			// Toast.makeText(PriceSettingActivity.this,
			// "Limited Price can not be empty.",
			// Toast.LENGTH_LONG).show();
			ShowMessage("Limited Qty can not be empty.",
					MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
			return -1;
		}
		

		if (!lq_amt.equals("") && lq_price.equals("")) {
			// Toast.makeText(PriceSettingActivity.this,
			// "Limited Price can not be empty.",
			// Toast.LENGTH_LONG).show();
			ShowMessage("Limited Price can not be empty.",
					MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
			return -1;
		}

		if (!lq_price.equals("") && isNum(lq_price) == false) {
			// Toast.makeText(PriceSettingActivity.this,
			// "Please enter a valid Limited Price.",
			// Toast.LENGTH_LONG).show();
			ShowMessage("Please enter a valid Limited Price.",
					MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
			return -1;
		}
		
		if (!lq_price.equals("") && Double.valueOf(lq_price) == 0 && !zeroPrice) {
			ShowMessage("Item Price cannot be zero.",
					MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
			et_lq_price.requestFocus();
			return -1;
		}

		if (!st_date.equals("") && st_time.equals("")) {
			// Toast.makeText(PriceSettingActivity.this,
			// "Start Time can not be empty.",
			// Toast.LENGTH_LONG).show();
			ShowMessage("Start Time can not be empty.",
					MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
			return -1;
		}

		if (!st_date.equals("") && st_time.equals("")) {
			// Toast.makeText(PriceSettingActivity.this,
			// "Start Time can not be empty.",
			// Toast.LENGTH_LONG).show();
			ShowMessage("Start Time can not be empty.",
					MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
			return -1;
		}

		if (!et_date.equals("") && et_time.equals("")) {
			// Toast.makeText(PriceSettingActivity.this,
			// "End Time can not be empty.",
			// Toast.LENGTH_LONG).show();
			ShowMessage("End Time can not be empty.", MessageDialog.ICON_INFO,
					MessageDialog.MESSAGE_BOX_OK);
			return -1;
		}

		if (st_date.equals("") && !st_time.equals("")) {
			// Toast.makeText(PriceSettingActivity.this,
			// "Start Date can not be empty.",
			// Toast.LENGTH_LONG).show();
			ShowMessage("Start Date can not be empty.",
					MessageDialog.ICON_INFO, MessageDialog.MESSAGE_BOX_OK);
			return -1;
		}

		if (et_date.equals("") && !et_time.equals("")) {
			// Toast.makeText(PriceSettingActivity.this,
			// "End Date can not be empty.",
			// Toast.LENGTH_LONG).show();
			ShowMessage("End Date can not be empty.", MessageDialog.ICON_INFO,
					MessageDialog.MESSAGE_BOX_OK);
			return -1;
		}

		if (!percent_amt.equals("") && Double.valueOf(percent_amt) > 100) {

			// Toast.makeText(PriceSettingActivity.this,
			// "Cannot be more than 100%.",
			// Toast.LENGTH_LONG).show();
			ShowMessage("Cannot be more than 100%.", MessageDialog.ICON_INFO,
					MessageDialog.MESSAGE_BOX_OK);
			return -1;
		}

		if (cp_price.equals("")) {
			// Toast.makeText(PriceSettingActivity.this,
			// "Current Price can not be empty.",
			// Toast.LENGTH_LONG).show();
			ShowMessage("Current Price can not be empty.",
					MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
			return -1;
		}

		Date curDate_s = null, curDate_e = null;
		DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
		// Date curDate =(Date)date;
		try {

			curDate_s = format1.parse(st_date);
			curDate_e = format1.parse(et_date);

		} catch (ParseException e) {
			e.printStackTrace();
		}

		if (!et_date.equals("") && !st_date.equals("")) {
			if (curDate_e.before(curDate_s)) {
				// Toast.makeText(PriceSettingActivity.this,
				// "End Date less than Start Date.",
				// Toast.LENGTH_LONG).show();
				ShowMessage("End Date cannot be earilier than Start Date.",
						MessageDialog.MESSAGE_BOX_OK, MessageDialog.ICON_INFO);
				return -1;
			}

			if (!st_time.equals("") && !et_time.equals("")) {
				if (et_date.equals(st_date)
						&& gettime_short(et_time) < gettime_short(st_time)) {
					// Toast.makeText(PriceSettingActivity.this,
					// "End Time less than Start Time.",
					// Toast.LENGTH_LONG).show();
					ShowMessage("End Time cannot be earilier than Start Time.",
							MessageDialog.MESSAGE_BOX_OK,
							MessageDialog.ICON_INFO);
					return -1;
				}
			}

		}

		return 1;
	}

	public static boolean isNum(String str) {
		return str.matches("^[-+]?(([0-9]+)([.]([0-9]+))?|([.]([0-9]+))?)$");
	}

	public OnItemSelectedListener onItemSelectedListener = new OnItemSelectedListener() {

		public void onItemSelected(AdapterView<?> parent, View view,
				int position, long id) {
			if (sp_items[position].equals("ALL")) {
				et_search.setEnabled(false);
			} else {
				et_search.setEnabled(true);
			}
		}

		public void onNothingSelected(AdapterView<?> arg0) {

		}
	};

	//

	public boolean BindingData(int page, int SPType, String searchString) {
		if (itemlist == null) {
			itemlist = new ArrayList<ItemSetting>();
			itemlist = itemservice.SearchItems(page, SPType,
					searchString);

			itemAdapter = new ItemListAdapter(this, itemlist);
			lv_items.setAdapter(itemAdapter);
			if (itemlist.size() > 0) {
				tv_page.setVisibility(View.VISIBLE);

				RefresItem(0);
				return true;
			} else {
				tv_page.setVisibility(View.INVISIBLE);
				tv_dupc.setText("");
				tv_dname.setText("");
				tv_ddesc.setText("");
				tv_dprice.setText("");
				Bitmap bp = mItemPicService.getImageByUPC("");
				if (bp == null) {
					Bitmap logo = BitmapFactory.decodeResource(PriceSettingActivity.this
							.getApplicationContext().getResources(),
							R.drawable.moleqlogo);
					iv_photo.setImageBitmap(logo);
				} else {
					iv_photo.setImageBitmap(bp);
				}
				setempty();
				et_cp_amt.setText("");
				et_cp_price.setText("");
				InitializeEnabledFalse();
				return false;
			}
		} else {
			itemlist.clear();
			itemlist = itemservice.SearchItems(page, SPType,
					searchString);
			itemAdapter.setSource(itemlist);
			itemAdapter.notifyDataSetChanged();
			if (itemlist.size() > 0) {
				tv_page.setVisibility(View.VISIBLE);
				// int index = itemAdapter.GetSelectedIndex();
				RefresItem(0);
				return true;
			} else {
				tv_page.setVisibility(View.INVISIBLE);
				tv_dupc.setText("");
				tv_dname.setText("");
				tv_ddesc.setText("");
				tv_dprice.setText("");
				Bitmap bp = mItemPicService.getImageByUPC("");
				if (bp == null) {
					Bitmap logo = BitmapFactory.decodeResource(PriceSettingActivity.this
							.getApplicationContext().getResources(),
							R.drawable.moleqlogo);
					iv_photo.setImageBitmap(logo);
				} else {
					iv_photo.setImageBitmap(bp);
				}
				setempty();
				et_cp_amt.setText("");
				et_cp_price.setText("");
				InitializeEnabledFalse();
				return false;
			}
		}

	}

	public void SetPage() {
		ibtn_backpage = (ImageButton) findViewById(R.id.ibtn_backpage);
		ibtn_nextpage = (ImageButton) findViewById(R.id.ibtn_nextpage);
		tv_page = (TextView) findViewById(R.id.tv_page);
		String pagetext = (String) tv_page.getText();
		int page = Integer.valueOf(pagetext);
		if (PageCountSize > page) {
			ibtn_nextpage.setEnabled(true);
			ibtn_nextpage.setVisibility(View.VISIBLE);
		} else {
			ibtn_nextpage.setEnabled(false);
			ibtn_nextpage.setVisibility(View.INVISIBLE);
		}

		if (PageCountSize > 1 && page > 1) {
			ibtn_backpage.setEnabled(true);
			ibtn_backpage.setVisibility(View.VISIBLE);
		} else {
			ibtn_backpage.setEnabled(false);
			ibtn_backpage.setVisibility(View.INVISIBLE);
		}
	}

	public class SP {
		public static final int Department = 0;
		public static final int SubDepartment = 1;
		public static final int UPC = 2;
		// public static final int ALL = 0;

	}

	public void Search() {
		et_search = (EditText) findViewById(R.id.et_search);
		 searchString = et_search.getText().toString();
//		
//		String sql = "";
//		String countSql = "select count(F01) from t_item_setting as a,t_uom_desc as b where a.F23 = b.F23 ";
		switch ((int) sp_list.getSelectedItemId()) {
	
		case SP.UPC:
			if (searchString != null && !searchString.trim().equals("")) {
				searchType = priceservice.UPC;
				if (searchString.length() < 14) {
					UPC upc = new UPC(searchString, UPC.INPUT_BY_MANUAL,
							GlobalInfo.getInstance().isNormalize);
					searchString = upc.code;
				}
				PageCountSize = itemservice.GetPageCountSize(
						searchType, searchString);
				if (BindingData(0, searchType, searchString) == false) {
					ShowMessage("Item Not Found.",
							MessageDialog.MESSAGE_BOX_OK,
							MessageDialog.ICON_INFO);
					//SetEnabledFalse();
				}
				//ControlEmpty();
				SetPage();
			} else {
				et_search.setText("");
				return;
			}
			break;
		case SP.SubDepartment:
			if (searchString != null && !searchString.trim().equals("")) {
				searchType = priceservice.SubDept;
				if (MoleQUtil.isNumeric(searchString)) {
					PageCountSize = itemservice.GetPageCountSize(
							searchType, searchString);
					if (BindingData(0, searchType, searchString) == false) {
						ShowMessage("Item Not Found.",
								MessageDialog.MESSAGE_BOX_OK,
								MessageDialog.ICON_INFO);
						//SetEnabledFalse();
					}
					SetPage();
				} else {
					if (itemlist != null) {
						itemlist.clear();
					}
				}
				//ControlEmpty();
			} else {
				et_search.setText("");
				return;
			}
			break;
		case SP.Department:
			if (searchString != null && !searchString.trim().equals("")) {
				searchType = priceservice.Department;
				if (MoleQUtil.isNumeric(searchString)) {
					PageCountSize = itemservice.GetPageCountSize(
							searchType, searchString);
					if (BindingData(0, searchType, searchString) == false) {
						ShowMessage("Item Not Found.",
								MessageDialog.MESSAGE_BOX_OK,
								MessageDialog.ICON_INFO);
						//SetEnabledFalse();
					}
					SetPage();
				} else {
					if (itemlist != null) {
						itemlist.clear();
					}
				}
				//ControlEmpty();
			} else {
				et_search.setText("");
				return;
			}
			break;
		}

	}

	public void SetEnabledTrue() {

		btn_update.setEnabled(false);
		btn_undo.setEnabled(false);
		btn_search.setEnabled(true);
		lv_items.setEnabled(true);
	}

	public void SetEnabledFalse() {

		btn_undo.setEnabled(true);
		btn_update.setEnabled(true);
		btn_search.setEnabled(false);
		ibtn_backpage.setEnabled(false);
		ibtn_nextpage.setEnabled(false);
		lv_items.setEnabled(false);
		ibtn_backpage.setVisibility(View.INVISIBLE);
		ibtn_nextpage.setVisibility(View.INVISIBLE);
		// tv_page.setVisibility(View.INVISIBLE);
	}

	public void InitializeEnabledTrue() {

		et_cp_amt.setEnabled(true);
		et_cp_price.setEnabled(true);
		et_da_price.setEnabled(true);
		et_et_date.setEnabled(true);
		et_et_time.setEnabled(true);
		et_lq_amt.setEnabled(true);
		et_lq_price.setEnabled(true);
		et_np_amt.setEnabled(true);
		et_np_price.setEnabled(true);
		et_percent_amt.setEnabled(true);
		et_pp_amt.setEnabled(true);
		et_pp_price.setEnabled(true);
		et_st_date.setEnabled(true);
		et_st_time.setEnabled(true);
		btn_mm.setEnabled(true);
		btn_discount_link.setEnabled(true);
		ibtn_clear_date.setEnabled(true);
		et_price_lvl.setEnabled(true);
	}

	public void InitializeEnabledFalse() {

		et_cp_amt.setEnabled(false);
		et_cp_price.setEnabled(false);
		et_da_price.setEnabled(false);
		et_et_date.setEnabled(false);
		et_et_time.setEnabled(false);
		et_lq_amt.setEnabled(false);
		et_lq_price.setEnabled(false);
		et_np_amt.setEnabled(false);
		et_np_price.setEnabled(false);
		et_percent_amt.setEnabled(false);
		et_pp_amt.setEnabled(false);
		et_pp_price.setEnabled(false);
		et_st_date.setEnabled(false);
		et_st_time.setEnabled(false);
		btn_mm.setEnabled(false);
		btn_discount_link.setEnabled(false);
		ibtn_clear_date.setEnabled(false);
		et_price_lvl.setEnabled(false);
	}

	public void Keyboard() {
		InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		inputMethodManager.hideSoftInputFromWindow(PriceSettingActivity.this
				.getCurrentFocus().getWindowToken(),
				InputMethodManager.HIDE_NOT_ALWAYS);
	}

	// =========== setup scanner =================
	public void onErrorEvent(String res) {
		// TODO Auto-generated method stub

	}

	public void onScannerEvent(String res) {
		sp_list.setSelection(SP.UPC);
		et_search.setText(res);
		Keyboard();
		tv_page.setText(String.valueOf(1));
		Pricemode = 0;
		this.Search();
		et_search.setText("");
		Pricemode = 1;
	}

	public void onTimeOutEvent() {
		// TODO Auto-generated method stub

	}

	public void onWeightEvent(int arg0) {
		// TODO Auto-generated method stub

	}

	private OnClickMessageListener onClickMessageListener = new OnClickMessageListener() {

		@Override
		public void onClickYes() {
			// TODO Auto-generated method stub
			mDeviceManager.disableAllScanner();
			mDeviceManager.disconnectAllScanner();
			mDeviceManager.resetALLDevices();
			finish();

		}

		@Override
		public void onClickNo() {
			// TODO Auto-generated method stub
			mMessageDialog.dismiss();
			mDeviceManager.clearAllScannerBuffer();
			mDeviceManager.enableAllScanner();
		}

		@Override
		public void onClickOK() {
			// TODO Auto-generated method stub
			mMessageDialog.dismiss();
			mDeviceManager.clearAllScannerBuffer();
			mDeviceManager.enableAllScanner();
		}

	};

	public void ShowMessage(String ls_msg, int style, int icon) {
		mMessageDialog = new MessageDialog(PriceSettingActivity.this);
		mMessageDialog.setStyle(style);
		mMessageDialog.setMessageIcon(icon);
		mMessageDialog.setMessage(ls_msg);
		mMessageDialog.setOnClickMessageListener(onClickMessageListener);
		mMessageDialog.show();
	}

	@Override
	public void onDataEvent(Object obj) {
		// TODO Auto-generated method stub
		
	}

	
	@Override
	public void onReturnValue(int what,Object obj) {
		// TODO Auto-generated method stub
		dis= (ItemDiscountSetting)obj;
		btn_discount_link.setText(String.valueOf(dis.getDs_desc()));
	}
	
	@Override
	public void onCloseWithReturn(Class<? extends MoleQBaseDialog> pramClass, int viewId, String parm) {
		super.onCloseWithReturn(pramClass, viewId, parm);
		
		Calendar c1 = Calendar.getInstance();
		mYear = c1.get(Calendar.YEAR);
		mMonth = c1.get(Calendar.MONTH) + 1;
		mDay = c1.get(Calendar.DAY_OF_MONTH);
		String time = String.format("%02d", 00) + ":"
				+ String.format("%02d", 00);
		String time2 = String.format("%02d", 23) + ":"
				+ String.format("%02d", 59);
		switch (viewId) {
		case R.id.et_st_date:
			et_st_date.setText(parm);
			if (et_st_time.getText().toString().equals("")) {
				et_st_time.setText(time);
			}
			break;
		case R.id.et_st_time:
			et_st_time.setText(parm);
			if (et_st_date.getText().toString().equals("")) {
				et_st_date.setText(mYear + "-" + String.format("%02d", mMonth) + "-" + mDay);
			}
			break;
		case R.id.et_et_date:
			et_et_date.setText(parm);
			if (et_et_time.getText().toString().equals("")) {
				et_et_time.setText(time2);
			}
			break;
		case R.id.et_et_time:
			et_et_time.setText(parm);
			if (et_et_date.getText().toString().equals("")) {
				et_et_date.setText(mYear + "-" + String.format("%02d", mMonth) + "-" + mDay);
			}
			break;
		default:
			break;
		}
		
	}
	
	
	
}